/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool find(TreeNode* root,TreeNode* p)
    {
        if(root==nullptr)
        {
            return false;
        }
        if(root==p) return true;

        return find(root->left,p)||find(root->right,p);

    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {

        if(root==p||root==q) return root;
        if(root==nullptr)
        {
            return nullptr;
        }
        if((find(root->left,p)&&find(root->right,q))||(find(root->left,q)&&find(root->right,p)))
        {
            return root;
        }
        TreeNode* ret1= lowestCommonAncestor(root->left,p,q);
        TreeNode* ret2= lowestCommonAncestor(root->right,p,q);

        if(ret1) return ret1;
        if(ret2) return ret2;

        return nullptr;
    }
};



//做法二更优做法
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    bool test(TreeNode* root,TreeNode* p,stack<TreeNode*>& st)
    {
        if(root==nullptr)
        {
            return false;
        }
        st.push(root);
        if(root==p)
        {
            return true;
        }
        
        if(test(root->left,p,st)) return true;
        if(test(root->right,p,st)) return true;

        st.pop();
        return false;
    }
    TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q) {  
        if(root==p||root==q) return root;
    stack<TreeNode*> st1;
    stack<TreeNode*> st2;
    test(root,p,st1);
    test(root,q,st2);    
    int ret=0;
    if(st1.size()>=st2.size())
    {
        ret=st1.size()-st2.size();
        while(ret--)
    {
        st1.pop();   
    }
    }
    else
    {
        ret=st2.size()-st1.size();
        while(ret--)
    {
        st2.pop();   
    }
    }
    

    while(st1.top()!=st2.top())
    {
        st1.pop();
        st2.pop();
    }
    return st1.top();
    }
};